import React, {Component} from "react";
import {HomeWrapper} from "@/component/Home/style";
import {Button, Col, Form, Input, InputNumber, Popover, Row, Select, Steps, Switch, Upload} from 'antd';
import {StepContent, StepsContainer, StepTitle} from "@/component/Feature/UploadGame/style";
import {
    CheckOutlined,
    ClearOutlined,
    CloseOutlined,
    GlobalOutlined,
    HighlightOutlined,
    PlusOutlined,
    RetweetOutlined,
    UnlockOutlined,
    VideoCameraAddOutlined
} from '@ant-design/icons';
import {getGameCompanyList} from '@/api/JustGameCompany';
import {getGameTypeList} from "@/api/JustGameType";
import Config from "@/config";
import {editorUpload, load, successMsg} from "@/util/global";
import {systemDeleteFile} from "@/util/Api";
import {getGamePlatformList} from "@/api/JustGamePlatform";
import {adminUpdateGameInfo, getGameEditDetail, saveGameInfo} from "@/api/JustGameInfo";
import BraftEditor from "braft-editor";
import HtmlPreview from "@/util/HtmlPreview";
import {Prompt} from "react-router-dom";
import {fromBase64, toBase64} from "@/util/CodeUtils";
import {commonUpload, commonUploadByKey} from "@/util/FileUtil";

const {Option} = Select;
const formItemLayout = {
    labelCol: {
        span: 6,
    },
    wrapperCol: {
        span: 14,
    },
};

class UploadGame extends Component {
    UploadGameForm = React.createRef();

    constructor(props) {
        super(props);
        this.handleClickSubmit = this.handleClickSubmit.bind(this);
        this.handleCloudResourceInputChange = this.handleCloudResourceInputChange.bind(this);
        this.handleResetCloudResource = this.handleResetCloudResource.bind(this);
        this.handleRemoveCloudResource = this.handleRemoveCloudResource.bind(this);
        this.handleAddCloudResource = this.handleAddCloudResource.bind(this);
        this.handleRemoveFileByKey = this.handleRemoveFileByKey.bind(this);
        this.handleRemoveFile = this.handleRemoveFile.bind(this);
        this.handleChangeState = this.handleChangeState.bind(this);
        this.handleEditorChange = this.handleEditorChange.bind(this);
        this.loadGameCompany = this.loadGameCompany.bind(this);
        this.loadGameType = this.loadGameType.bind(this);
        this.shouldAskSave = this.shouldAskSave.bind(this);
        this.loadGamePlatform = this.loadGamePlatform.bind(this);
        this.handleClickEdit = this.handleClickEdit.bind(this);
        let isSave = this.props.location.pathname === '/upload-game';


        this.state = {
            current: 0,
            gameInfo: {
                id: '',
                cnName: null,
                enName: null,
                images: null,
                types: [],
                desc: null,
                companyId: null,
                cost: 0,
                isVip: false,
                platforms: [],
                isUseOldResource: true,
                website: "",
            },
            companyList: [],
            typeList: [],
            fileItems: [],
            platformList: [],
            clouds: [],
            snapshotItems: [],
            video: [],
            editorState: null,
            isSave,
            confirmVisible: false

        };
        if (!isSave && this.props.location.query) {
            load(true)
            getGameEditDetail(this.props.location.query.gameInfoId)
                .then(res => {
                    //查询到信息后初始化页面
                    let gameInfo = {
                        id: res.data.id,
                        cnName: res.data.cnName,
                        enName: res.data.enName,
                        images: res.data.images,
                        website: res.data.website,
                        types: res.data.types ? res.data.types : [],
                        desc: BraftEditor.createEditorState(res.data.desc),
                        companyId: res.data.companyId,
                        cost: res.data.cost,
                        isVip: res.data.isVip === 1,
                        platforms: res.data.platforms ? res.data.platforms : [],
                        editorState: BraftEditor.createEditorState(res.data.desc),
                        isUseOldResource: true,
                    }
                    this.setState({
                        gameInfo,
                        fileItems: res.data.images ? [
                            {
                                status: 'done',
                                imgUrl: res.data.images,
                                url: res.data.images
                            }
                        ] : [],
                        snapshotItems: res.data.gamePictures ?
                            res.data.gamePictures.map(str => {
                                return {status: 'done', imgUrl: str, url: str}
                            }) : [],
                        video: res.data.videoUrl ? [
                            {
                                name: res.data.videoUrl,
                                status: 'done',
                                imgUrl: res.data.videoUrl,
                                url: res.data.videoUrl
                            }
                        ] : [],
                        clouds: []
                    })
                    this.UploadGameForm.current.setFieldsValue(gameInfo);
                    load(false)
                })
        }
    }

    shouldAskSave() {
        const {gameInfo} = this.state;
        let count = 0;
        Object.keys(gameInfo).forEach(key => {
            if (gameInfo[key] && gameInfo[key].length > 0) count++;
        })
        return count > 3;
    }

    componentDidMount = () => {
        if (this.state.isSave && localStorage.getItem('upload-game-temp')) {
            let shouldReloadTemp = window.confirm("是否恢复草稿信息？")
            if (shouldReloadTemp) {
                let State = JSON.parse(fromBase64(localStorage.getItem('upload-game-temp')))
                this.setState(State);
                let resetForm = {
                    ...State,
                    ...State.gameInfo
                }
                this.UploadGameForm.current.setFieldsValue(resetForm);
            }
            localStorage.removeItem('upload-game-temp');
        }
        this.loadGameCompany();
        this.loadGameType();
        this.loadGamePlatform();
    }

    /**
     * 加载游戏平台信息
     */
    loadGamePlatform() {
        getGamePlatformList()
            .then(response => {
                if (response.success) {
                    this.setState({
                        platformList: response.data.rows
                    })
                }
            });
    }


    /**
     * 加载游戏厂商信息
     */
    loadGameCompany() {
        getGameCompanyList()
            .then(response => {
                if (response.success) {
                    console.log('response.data.rows', response.data.rows)
                    this.setState({
                        companyList: response.data.rows
                    })
                }
            });
    }

    /**
     * 加载游戏类型信息
     */
    loadGameType() {
        getGameTypeList()
            .then(response => {
                if (response.success) {
                    this.setState({
                        typeList: response.data.rows
                    })
                }
            });
    }

    handleChangeState(key, e) {
        console.log(e)
        if (key !== 'isUseOldResource' && !e) {
            return;
        } else if (key === 'isUseOldResource') {
            this.setState({
                clouds: []
            })
        }
        let gameInfo = this.state.gameInfo;
        if (e.target) {
            gameInfo[key] = e.target.value;
        } else {
            gameInfo[key] = e;
        }
        this.setState({
            gameInfo
        });
    }

    stepTitle(str) {
        return <>
            <StepTitle>{str}</StepTitle>
        </>
    }

    stepContent(str) {
        return <>
            <StepContent>{str}</StepContent>
        </>
    }

    handleRemoveFile(file) {
        return new Promise((resolve, reject) => {
            if (this.state.isSave) {
                systemDeleteFile({path: file.imgUrl})
                    .then(res => {
                        resolve(res.success);
                    })
            } else {
                resolve(true);
            }
        }).then(r => {
            if (r) {
                const removed = this.state.fileItems.filter(item => item.uid !== file.uid);
                this.setState({
                    fileItems: removed
                })
            }
        });
    }

    handleRemoveCloudResource(index) {
        let {clouds} = this.state;
        clouds.splice(index, 1);
        this.setState({
            clouds
        })
    }

    handleResetCloudResource(index) {
        let {clouds} = this.state;
        clouds[index] = {title: '', path: '', secretKey: ''};
        this.setState({
            clouds
        })
    }

    handleAddCloudResource() {
        let {clouds} = this.state;
        if (clouds.length === 3) return;
        clouds.push({title: '', path: '', secretKey: ''});
        this.setState({
            clouds
        })
    }

    handleRemoveFileByKey(file, KeyStr) {
        return new Promise((resolve, reject) => {
            if (this.state.isSave) {
                systemDeleteFile({path: file.imgUrl})
                    .then(res => {
                        resolve(res.success);
                    })
            } else {
                resolve(true);
            }
        }).then(r => {
            if (r) {
                const removed = this.state[KeyStr].filter(item => item.uid !== file.uid);
                let state = this.state;
                state[KeyStr] = removed;
                this.setState(state)
            }
        });
    }

    handleCloudResourceInputChange(e, index, key) {
        let {clouds} = this.state;
        console.log('e', e);
        clouds[index][key] = e.target.value;
        this.setState({
            clouds
        })
    }

    async handleEditorChange(editorState) {
        this.setState({editorState})
    }

    buildPostData() {
        let additions = [];
        if (this.state.video && this.state.video.length > 0) {
            additions.push({
                type: 2,
                url: this.state.video[0].imgUrl
            })
        }
        if (this.state.snapshotItems && this.state.snapshotItems.length > 0) {

            this.state.snapshotItems.forEach(item => {
                additions.push({
                    type: 1,
                    url: item.imgUrl
                })
            })
        }
        return {
            ...this.state.gameInfo,
            images: this.state.fileItems ? this.state.fileItems[0].imgUrl : null,
            isVip: this.state.gameInfo.isVip ? 1 : 0,
            clouds: this.state.clouds,
            additions,
            desc: this.state.editorState ? this.state.editorState.toRAW() : null,
        };
    }

    handleClickEdit() {
        this.UploadGameForm.current.validateFields().then(r => {
            adminUpdateGameInfo(this.buildPostData()).then(response => {
                if (response.success) {
                    successMsg("更新成功！")
                    window._ROUTER_.push('/home');
                }
            })
        })
    }

    handleClickSubmit() {
        this.UploadGameForm.current.validateFields().then(r => {
            saveGameInfo(this.buildPostData()).then(response => {
                if (response.success) {
                    successMsg("提交成功！")
                    window._ROUTER_.push('/home');
                }
            })
        })
    }

    render() {
        const controls = [
            {
                key: 'custom-button',
                type: 'button',
                text: '效果预览',
                onClick: () => HtmlPreview(this.state.editorState)
            },
            {
                key: 'bold',
                text: <b>加粗</b>
            },
            'italic', 'underline', 'separator', 'link', 'separator'
        ]
        const onFinish = (values) => {
            console.log('Received values of form: ', values);
        };

        const {Step} = Steps;
        return <>
            <HomeWrapper style={{backgroundColor: '#fff'}}>
                <Prompt message={
                    (location) => {
                        if (this.shouldAskSave() && this.state.isSave) {
                            let needSaveTemp = window.confirm("需要保存页面到草稿吗？")
                            if (needSaveTemp) {
                                let copyState = toBase64(JSON.stringify(this.state));
                                localStorage.setItem('upload-game-temp', copyState);
                            }
                        }
                        return true;
                    }
                }/>
                <Form
                    ref={this.UploadGameForm}
                    style={{marginBottom: '200px'}}
                    name="validate_other"
                    {...formItemLayout}
                    onFinish={onFinish}
                    initialValues={{
                        'input-number': 3,
                        'checkbox-group': ['A', 'B'],
                        rate: 3.5,
                    }}
                >

                    <Form.Item label="当前状态：">
                        <span className="ant-form-text">{this.state.isSave ? "发布游戏资源" : "更新游戏资源"}</span>
                    </Form.Item>

                    <Form.Item label={"封面图片"}
                               name={'images'}
                               rules={[{required: true, message: '图片不能为空！'}]}
                    >
                        <Upload
                            fileList={this.state.fileItems}
                            listType="picture-card"
                            maxCount={1}
                            showUploadList={true}
                            accept=".png, .jpg, .jpeg, .bmp, .svg"
                            customRequest={(options) => commonUpload(this, options)}
                            onRemove={(file) => this.handleRemoveFile(file)}
                        >
                            {
                                this.state.fileItems && this.state.fileItems[0] ?
                                    null :
                                    <div>
                                        <PlusOutlined/>
                                        <div style={{marginTop: 8}}>点击上传</div>
                                    </div>
                            }
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        name="cnName"
                        label="中文名称"
                        rules={[{required: true, message: '请输入中文名称'}]}
                    >
                        <Input placeholder="在此输入中文名称"
                               value={this.state.gameInfo.cnName}
                               onChange={(e) => this.handleChangeState('cnName', e)}
                               allowClear/>
                    </Form.Item>

                    <Form.Item
                        name="enName"
                        label="英文名称"
                        rules={[{required: true, message: '请输入英文名称'}]}
                    >
                        <Input placeholder="在此输入英文名称"
                               value={this.state.gameInfo.enName}
                               onChange={(e) => this.handleChangeState('enName', e)}
                               allowClear/>
                    </Form.Item>

                    <Form.Item
                        name="companyId"
                        label="游戏厂商"
                        hasFeedback
                        rules={[{required: true, message: '请选择游戏厂商'}]}
                    >
                        <Select placeholder="点击选择游戏厂商"
                                value={this.state.gameInfo.companyId}
                                onChange={(e) => this.handleChangeState('companyId', e)}
                                allowClear>
                            {
                                this.state.companyList ?
                                    this.state.companyList.map(info => {
                                        console.log('companyList', info)
                                        return <Option value={info.id} key={info.id}>{info.name}</Option>
                                    }) : null
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="platforms"
                        label="游戏平台 / 环境"
                        hasFeedback
                        rules={[{required: true, message: '请选择游戏平台', type: 'array'}]}
                    >
                        <Select placeholder="点击选择游戏厂商"
                                mode="multiple"
                                value={this.state.gameInfo.platforms}
                                onChange={(e) => this.handleChangeState('platforms', e)}
                                allowClear>
                            {
                                this.state.platformList ?
                                    this.state.platformList.map(info => {
                                        return <Option value={info.id}
                                                       key={info.id}>{info.name} 版本：{info.version} ({info.notice})</Option>

                                    }) : null
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="types"
                        label="游戏类型"
                        rules={[{required: true, message: '请选择游戏类型', type: 'array'}]}
                    >
                        <Select placeholder="点击选择游戏类型"
                                mode="multiple"
                                value={this.state.gameInfo.types}
                                onChange={(e) => this.handleChangeState('types', e)}
                                allowClear>
                            {
                                this.state.typeList ?
                                    this.state.typeList.map(info => {
                                        return <>
                                            <Option value={info.id} key={info.id}>{info.chineseName}</Option>
                                        </>
                                    }) : null
                            }
                        </Select>
                    </Form.Item>
                    <Form.Item
                        name="website"
                        label="官方网站"
                        rules={[{required: true, message: '请输入官方网站'}]}
                    >
                        <Input placeholder="在此输入官方网站"
                               value={this.state.gameInfo.website}
                               onChange={(e) => this.handleChangeState('website', e)}
                               allowClear/>
                    </Form.Item>
                    <Form.Item
                        label={`游戏截图 ${this.state.snapshotItems.length}/8`}
                        name={'snapshots'}
                    >
                        <Upload
                            fileList={this.state.snapshotItems}
                            listType="picture-card"
                            maxCount={8}
                            showUploadList={true}
                            accept=".png, .jpg, .jpeg, .bmp, .svg"
                            customRequest={(options) => commonUploadByKey(this, options, 'snapshotItems')}
                            onRemove={(file) => this.handleRemoveFileByKey(file, 'snapshotItems')}
                        >
                            {
                                this.state.snapshotItems.length < 8
                                    ?
                                    <div>
                                        <PlusOutlined/>
                                        <div style={{marginTop: 8}}>点击上传</div>
                                    </div>
                                    :
                                    null
                            }
                        </Upload>
                    </Form.Item>
                    <Form.Item
                        name="cost"
                        label="所需JCoins币">
                        <Form.Item name="input-number" noStyle>
                            <InputNumber min={0} max={100} defaultValue={0}
                                         onChange={(e) => this.handleChangeState('cost', e)}
                                         value={this.state.gameInfo.cost}/>
                        </Form.Item>
                        <Config.IconFont type={'icon-jinbi'} style={{
                            fontSize: '20px',
                            textAlign: 'left',
                            marginLeft: '10px'
                        }}/>
                    </Form.Item>

                    <Form.Item name="switch"
                               label={
                                   <Popover content="开启后则该资源只允许VIP用户下载，若同时是免费资源将给予一定积分作为奖励。"
                                            overlayStyle={{position: "fixed"}}
                                            destroyTooltipOnHide={true}
                                            placement={"top"}>
                            <span>
                            <Config.IconFont style={{fontSize: '15px', color: '#686868'}}
                                             type={'icon-gantanhao-xianxingyuankuang'}/>&nbsp;VIP资源
                            </span>
                                   </Popover>}>
                        <Switch checkedChildren={<CheckOutlined/>}
                                unCheckedChildren={<CloseOutlined/>}
                                value={this.state.gameInfo.isVip}
                                onChange={(e) => this.handleChangeState('isVip', e)}
                        />
                    </Form.Item>
                    <Form.Item
                        name='video'
                        label={
                            <Popover content="请勿上传大于20MB大小的视频文件，否则会导致上传失败！"
                                     overlayStyle={{position: "fixed"}}
                                     destroyTooltipOnHide={true}
                                     placement={"top"}
                            >
                            <span>
                            <Config.IconFont style={{fontSize: '15px', color: '#686868'}}
                                             type={'icon-gantanhao-xianxingyuankuang'}/>&nbsp;{`相关视频资源 ${this.state.video.length}/1`}
                            </span>
                            </Popover>}>
                        <Upload
                            fileList={this.state.video}
                            maxCount={1}
                            accept=".swf, .flv, .mp3, .mp4, .wav, .wma, .wmv, .mid, .avi, .mpg, .asf, .rm, .rmvb, .webm"
                            customRequest={(options) => commonUploadByKey(this, options, 'video')}
                            onRemove={(file) => this.handleRemoveFileByKey(file, 'video')}
                        >
                            <Button icon={<VideoCameraAddOutlined/>} disabled={this.state.video.length !== 0}>
                                点此上传音频资源
                            </Button>
                        </Upload>
                    </Form.Item>

                    {
                        this.state.video[0] && this.state.video[0].status === 'done' ?
                            <Form.Item label={"视频预览"}>
                                <video controls width={600}>
                                    <source src={this.state.video[0].imgUrl} type={"video/mp4"}/>
                                    您的浏览器不支持不支持H5播放器，请更新浏览器至最新版本！
                                </video>
                            </Form.Item>
                            :
                            null
                    }
                    <Form.Item label={`网盘资源 ${this.state.clouds.length}/3`} name={"clouds"}>
                        <Row gutter={[16, 5]} style={{marginTop: '5px', marginBottom: '30px', padding: '0 10px'}}>
                            {
                                !this.state.isSave ?
                                    <>
                                        <label style={{fontSize: '12px'}}>
                                            <p>
                                                为保护您的权益，该项暂不支持编辑或修改。
                                            </p>
                                            <p>
                                                是否保留之前的网盘资源信息？
                                                <Switch checkedChildren={"是"}
                                                        unCheckedChildren={"否"}
                                                        defaultChecked
                                                        size="small"
                                                        value={this.state.gameInfo.isUseOldResource}
                                                        onChange={(e) => this.handleChangeState('isUseOldResource', e)}
                                                />
                                            </p>
                                        </label>
                                    </>
                                    :
                                    null
                            }

                            {
                                this.state.clouds.map((item, index) => {
                                    return <Row gutter={[16, 16]} key={index}>
                                        <Col span={24}/>
                                        <Col span={5} style={{textAlign: 'right'}}>
                                            资源标题：
                                        </Col>
                                        <Col span={17} style={{textAlign: 'left'}}>
                                            <Input value={item.title}
                                                   prefix={<HighlightOutlined
                                                       style={{color: '#999999', marginRight: '5px'}}/>}
                                                   placeholder={"建议填写重要信息（ 如: \"版本\" + \"容量\" + \"须知\" ）"}
                                                   onChange={(e) => this.handleCloudResourceInputChange(e, index, 'title')}
                                            />
                                        </Col>
                                        <Col span={5} style={{textAlign: 'right'}}>
                                            网盘地址：
                                        </Col>
                                        <Col span={17} style={{textAlign: 'left'}}>
                                            <Input value={item.path}
                                                   prefix={<GlobalOutlined
                                                       style={{color: '#999999', marginRight: '5px'}}/>}
                                                   placeholder={"建议使用稳定资源地址（如：百度网盘、阿里云网盘）"}
                                                   onChange={(e) => this.handleCloudResourceInputChange(e, index, 'path')}
                                            />
                                        </Col>
                                        <Col span={5} style={{textAlign: 'right'}}>
                                            提取码：
                                        </Col>
                                        <Col span={17} style={{textAlign: 'left'}}>
                                            <Input value={item.secretKey}
                                                   placeholder={'提取码（非必填）'}
                                                   prefix={<UnlockOutlined
                                                       style={{color: '#999999', marginRight: '5px'}}/>}
                                                   onChange={(e) => this.handleCloudResourceInputChange(e, index, 'secretKey')}
                                            />
                                        </Col>
                                        <Col span={24} offset={9}>
                                            <Row>
                                                <Col span={4}>
                                                    <Button icon={<CloseOutlined/>}
                                                            onClick={() => this.handleRemoveCloudResource(index)}>删除</Button>
                                                </Col>
                                                <Col span={4}>
                                                    <Button icon={<RetweetOutlined/>}
                                                            onClick={() => this.handleResetCloudResource(index)}>重置</Button>
                                                </Col>
                                            </Row>
                                        </Col>
                                        <Col span={24}/>
                                    </Row>
                                })
                            }
                        </Row>
                        <Button type="dashed"
                                onClick={() => this.handleAddCloudResource()}
                                block
                                disabled={
                                    this.state.isSave ?
                                        this.state.clouds.length === 3 :
                                        this.state.gameInfo.isUseOldResource || this.state.clouds.length === 3
                                }
                                size={"large"}
                                icon={<PlusOutlined/>}>
                            添加
                        </Button>
                    </Form.Item>
                    <Form.Item name={"editorState"} label={"游戏描述"}>
                        <BraftEditor
                            controls={controls}
                            textBackgroundColor={false}
                            style={{border: '1px solid #888'}}
                            value={this.state.editorState}
                            onChange={this.handleEditorChange}
                            media={{uploadFn: editorUpload}}
                        />
                    </Form.Item>
                    <Form.Item wrapperCol={{offset: 11, span: 24}}>
                        {
                            this.state.isSave ?
                                <Button type="primary"
                                        htmlType="submit"
                                        icon={<CheckOutlined/>}
                                        onClick={this.handleClickSubmit}
                                >提交</Button>
                                :
                                <Button type="primary"
                                        htmlType="submit"
                                        icon={<CheckOutlined/>}
                                        onClick={this.handleClickEdit}
                                >更新</Button>
                        }
                        <Button style={{margin: '0 8px'}}
                                onClick={() => this.UploadGameForm.current.resetFields()}
                                icon={<ClearOutlined/>}>清空</Button>
                    </Form.Item>

                </Form>

                <StepsContainer>
                    <Steps current={0}>
                        <Step title={this.stepTitle("填写资料")}
                              description={this.stepContent("完善的资料可快速过审并且获取更高的关注度哦！")}/>
                        <Step title={this.stepTitle("提交审核")}
                              description={this.stepContent("提交资料后会由后台人员审核！")}/>
                        <Step title={this.stepTitle("等待审核结果")}
                              description={this.stepContent("审核通过后在全站可搜索到。被驳回可修改相关信息并重新提交审核！")}/>
                    </Steps>
                </StepsContainer>
            </HomeWrapper>
        </>
    }
}

export default UploadGame;
